import { clearMenuStorage, clearRolesStorage, clearToken, getToken } from '@/utils/auth';
import { Message } from '@arco-design/web-vue';
import axios from 'axios';

// 创建 axios 实例
const axiosInstance = axios.create({
    baseURL: 'http://192.168.110.29:8383/system',  // 设置基础 URL
    // baseURL: 'http://publicservice.chaohai.cyou/system',  // 设置基础 URL
    timeout: 5000,  // 设置请求超时时间,
});

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config: any) => {
        config.headers['accept-token'] = getToken()
        //post
        if (config.method === 'post') {
            config.headers['Content-Type'] = 'multipart/form-data'
            if (config?.data && Object.keys(config?.data).length !== 0) {
                const formData = new FormData();
                Object.keys(config?.data).forEach(key => {
                    formData.append(key, config?.data[key]);
                });
                config.data = formData
            }
        }
        // get
        if (config.method === 'get') {
            let url = config.url
            if (config?.data && Object.keys(config?.data).length !== 0) {
                Object.keys(config?.data).forEach((key, index) => {
                    if (index === 0) {
                        url += `?${key}=${config?.data[key]}`
                    } else {
                        url += `&${key}=${config?.data[key]}`
                    }
                });
            }
            config.url = url
        }
        return config;
    },
    error => {
        // 对请求错误做些什么
        return Promise.reject(error);  // 返回 Promise 以确保对错误的处理
    }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
    response => {
        if (response.data.code === 10000 || response.data.code === 10001) {
            setTimeout(() => {
                clearToken()
                clearRolesStorage()
                clearMenuStorage()
                window.location.href = '/'
            }, 500);
        }
        if (response.data.code !== 1) {
            Message.error(response.data.msg || '系统错误')
        }
        return response.data;
    },
    error => {
        Message.error(error?.response?.data?.msg || '系统错误')
        // token失效
        if (error?.response?.data?.code === 10000 || error?.response?.data?.code === 10001) {
            setTimeout(() => {
                clearToken()
                clearRolesStorage()
                clearMenuStorage()
                window.location.href = '/'
            }, 500);
        }
        return Promise.reject(error);
    }
);


export default axiosInstance